<template>
  <div>
    <Category :scene="scene" />
    <el-card style="margin: 10px 0">
      <!-- 属性列表 -->
      <div v-show="scene == 0">
        <el-button
          type="primary"
          size="default"
          icon="Plus"
          :disabled="!categoryStore.category3Id"
          @click="handleAddAttr"
        >
          添加平台属性
        </el-button>
        <el-table style="margin: 10px 0" :data="attrList" border>
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="80"
          ></el-table-column>
          <el-table-column
            label="属性名称"
            width="120"
            prop="attrName"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-tag
                style="margin: 5px"
                v-for="(item, index) in row.attrValueList"
                :key="item.id"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #="{ row, $index }">
              <el-button
                type="primary"
                size="default"
                icon="Edit"
                @click="handleEditAttr(row)"
              ></el-button>
              <el-popconfirm
                :title="`确定删除${row.attrName}属性？`"
                @confirm="handleDeleteAttr(row)"
              >
                <template #reference>
                  <el-button
                    type="danger"
                    size="default"
                    icon="Delete"
                  ></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 新增 -->
      <div v-show="scene == 1">
        <el-form inline>
          <el-form-item label="属性名称">
            <el-input
              v-model="attrParams.attrName"
              placeholder="请输入属性名称"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          size="default"
          icon="plus"
          :disabled="!attrParams.attrName"
          @click="hanldeAddAttrValue"
        >
          添加属性值
        </el-button>
        <!-- <el-button size="default">取消</el-button> -->
        <el-table
          style="margin: 10px 0"
          :data="attrParams.attrValueList"
          border
        >
          <el-table-column
            label="序号"
            width="80"
            type="index"
            align="center"
          ></el-table-column>
          <el-table-column label="属性值名称">
            <template #="{ row, $index }">
              <el-input
                :ref="(vc: any) => (inputArr[$index] = vc)"
                v-model="row.valueName"
                placeholder="请输入属性值名称"
                v-if="row.flag"
                size="small"
                @blur="toLook(row, $index)"
              ></el-input>
              <div v-else @click="($event) => toEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button
                type="danger"
                size="default"
                icon="delete"
                @click="handleDeleteAttrValue($index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          size="default"
          :disabled="attrParams.attrValueList.length == 0"
          @click="handleSave"
        >
          保存
        </el-button>
        <el-button size="default" @click="handleCancel">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="Attr">
import useCategoryStore from '@/store/modules/category'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import {
  getAttrInfoListApi,
  addOrUpdateAttrApi,
  deleteAttrApi,
} from '@/api/product/attr'
import {
  AttrResponseData,
  AttrList,
  Attr,
  AttrValue,
} from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'

const categoryStore = useCategoryStore()

const attrList = ref<AttrList>([])
const scene = ref<number>(0)
let attrParams = reactive<Attr>({
  attrName: '',
  attrValueList: [],
  categoryId: '',
  categoryLevel: 3,
})
const inputArr = ref<any>([])

watch(
  () => categoryStore.category3Id,
  () => {
    attrList.value = []
    if (categoryStore.category3Id) {
      getAttrList()
    }
  },
)

onBeforeUnmount(() => {
  categoryStore.$reset()
})

const getAttrList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore

  const res: AttrResponseData = await getAttrInfoListApi(
    category1Id,
    category2Id,
    category3Id,
  )
  if (res.code == 200) {
    attrList.value = res.data
  }
}

const handleAddAttr = () => {
  // 先清空数据
  Object.assign(attrParams, {
    attrName: '',
    attrValueList: [],
    categoryId: categoryStore.category3Id,
    categoryLevel: 3,
  })

  scene.value = 1
}

const handleEditAttr = (row: Attr) => {
  scene.value = 1

  Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}

const handleDeleteAttr = async (row: Attr) => {
  const res = await deleteAttrApi(row.id)
  if (res.code == 200) {
    ElMessage.success('删除成功')
    getAttrList()
  } else {
    ElMessage.error('删除失败')
  }
}

const hanldeAddAttrValue = () => {
  attrParams.attrValueList.push({
    valueName: '',
    flag: true,
  })
  nextTick(() => {
    inputArr.value[attrParams.attrValueList.length - 1].focus()
  })
}

const handleDeleteAttrValue = ($index: number) => {
  attrParams.attrValueList.splice($index, 1)
}

const handleSave = async () => {
  const res = await addOrUpdateAttrApi(attrParams)
  if (res.code == 200) {
    scene.value = 0
    ElMessage.success(attrParams.id ? '修改成功' : '添加成功')
    getAttrList()
  } else {
    ElMessage.error(attrParams.id ? '修改失败' : '添加失败')
  }
}

const handleCancel = () => {
  scene.value = 0
}

const toLook = (row: AttrValue, $index: number) => {
  // 不能为空
  if (row.valueName.trim() == '') {
    ElMessage.error('属性值名称不能为空')
    attrParams.attrValueList.splice($index, 1)
    return
  }
  // 属性值相同
  const repeat = attrParams.attrValueList.find((item) => {
    if (item != row) {
      return item.valueName == row.valueName
    }
  })
  if (repeat) {
    attrParams.attrValueList.splice($index, 1)
    ElMessage.error('属性值名称不能重复')
    return
  }

  row.flag = false
}

const toEdit = (row: AttrValue, $index: number) => {
  row.flag = true

  nextTick(() => {
    inputArr.value[$index].focus()
  })
}
</script>

<style scoped lang="scss"></style>
